package com.gaussian.property.app.controller.openapi;

import com.gaussian.property.app.service.AppUserService;
import com.gaussian.property.app.vo.IcsUser;
import com.gaussian.property.module.biz.entity.AppUser;
import com.gaussian.property.module.biz.service.IAppUserService;
import com.songqi.common.core.constant.Constants;
import com.songqi.common.core.domain.R;
import com.songqi.common.core.exception.CustomException;
import com.songqi.common.core.threadpool.AsyncManager;
import com.songqi.common.core.utils.sign.Md5Utils;
import com.songqi.common.log.service.AsyncLog;
import com.songqi.common.security.auth.WechatAuthenticationToken;
import com.songqi.common.security.model.JwtTokenPair;
import com.songqi.common.security.model.LoginUser;
import com.songqi.common.security.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @description:
 * @author: songqi(13776346982)
 * @date: 2023/3/13 20:05
 */
@RestController
@RequestMapping("/api/")
@Api(tags = "对外开放接口")
public class OpenApiController {


    @Resource
    private AppUserService appUserService;

    @Resource
    private IAppUserService iAppUserService;


    @Resource
    private AsyncLog asyncLog;


    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private TokenService tokenService;

    @Value("${application.http-sign-secret}")
    private String secret;

    @ApiOperation("同步ics系统的用户信息，返回本系统的token。前端请求本系统时，将token放在请求头中。")
    @PostMapping("synchronizeUser")
    public R<JwtTokenPair> synchronizeUser(@ApiParam("6位随机字符串") @RequestHeader("nonce") String nonce,
                                     @ApiParam("当前时间戳。纯数字，不需要格式化") @RequestHeader("timeStamp") String timeStamp,
                                     @ApiParam("签名。将timeStamp+nonce+密钥拼成一个字符串，使用Md5签名") @RequestHeader("sign")String sign,
                                   @RequestBody IcsUser icsUser) {
//        String hashSign = Md5Utils.hash(timeStamp + nonce + secret);
//        if(!hashSign.equals(sign)){
//            throw new CustomException("sign参数错误");
//        }
        AppUser appUser = appUserService.convert2AppUser(icsUser);
        appUserService.synchronizeIcsUser(icsUser, appUser);

        //authenticationManager.authenticate方法会去调用WechatAuthenticationProvider.authenticate方法，
        // 对appUserId进行验证。
        Authentication authentication = authenticationManager
                .authenticate(new WechatAuthenticationToken(appUser.getAppUserId(), null));
        AsyncManager.me().execute(asyncLog.recordLoginInfo(appUser.getAppUserId(), Constants.LOGIN_SUCCESS, "登录成功"));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        JwtTokenPair jwtTokenPair = tokenService.createToken(loginUser);
        appUser.setToken(jwtTokenPair.getAccessToken());
        appUser.setRefreshToken(jwtTokenPair.getRefreshToken());
        iAppUserService.updateById(appUser);
        return R.success(jwtTokenPair);
    }
}
